﻿using Admin.Core.Common.Attributes;
using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Quality;
using Admin.Core.Repository.Quality;
using Admin.Core.Repository.Quality.CheckReport;
using Admin.Core.Service.Quality.CheckReport.Input;
using Admin.Core.Service.Quality.CheckReport.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Quality.CheckReport
{
    public class CheckReportService: ICheckReportService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly ICheckReportRepository _checkReportRepository;
        private readonly IMachineCheckRepository _machineCheckRepository;
        public CheckReportService(IUser user, IMapper mapper
            , IMachineCheckRepository machineCheckRepository
            , ICheckReportRepository checkReportRepository)
        {
            _user = user;
            _mapper = mapper;
            _machineCheckRepository = machineCheckRepository;
            _checkReportRepository = checkReportRepository;
        }

        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var entity = await _machineCheckRepository.baseRepository.Select.Where(x => x.Id == id)
                 .LeftJoin(a => a.CheckReports.AsSelect().Any(x => x.MachineCheckId == a.Id))
                .IncludeMany(a => a.CheckReports, then => then.Where(x =>  x.Status == 0))
                .ToOneAsync();
            if (entity.CheckReports.Count > 1 || entity.CheckReports.Count == 0)
            {
                return ResponseOutput.NotOk("校准报告数据状态异常，请联系技术人员处理");
            }
            var entityDto = _mapper.Map<CheckReportGetOutput>(entity.CheckReports.FirstOrDefault());
            return ResponseOutput.Ok(entityDto);
        }

        public async Task<IResponseOutput> PageAsync(PageInput<CheckReportFilterInput> input)
        {
            var key = input.Filter?.Name;
            var id = input.Filter?.Id;
            var list = await _checkReportRepository.baseRepository.Select
            .WhereIf(key.NotNull(), a => a.MachineCheck.EquipmentName.Contains(key))
            .WhereIf(id != null, a => a.MachineCheckId.Equals(id))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(x => new CheckReportListOutput
            {
                 Status = x.Status ==0 ? "待确认" : x.Status == 1 ? "校验成功" : x.Status == 2 ? "校验失败" : "",
            });
            var data = new VxePageOutPut<CheckReportListOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };
            //var data = new PageOutput<MachineCheckListOutput>()
            //{
            //    List = list,
            //    Total = total
            //};
            return ResponseOutput.Ok(data);
        }


        [Transaction]
        public async Task<IResponseOutput> AddAsync(CheckReportAddInput input)
        {
            var entity = _mapper.Map<CheckReportEntity>(input);
            entity.Status = 0; //待确认
            entity.TenantId = _user.TenantId;
            entity.CalUserId = _user.Id;
            var id = (await _checkReportRepository.baseRepository.InsertAsync(entity)).Id;
            //if (id > 0)
            //{
                var machineCheck = await _machineCheckRepository.baseRepository.Select.Where(x => x.Id == input.MachineCheckId).ToOneAsync();
                machineCheck.Status = 1;
                var mid = await _machineCheckRepository.UpdateAsync(machineCheck);
                return ResponseOutput.Result(mid > 0);
            //}
            //else
            //{
            //    return ResponseOutput.NotOk("失败！");
            //}
           
        }


        public async Task<IResponseOutput> UpdateAsync(CheckReportUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }
            var entity = await _checkReportRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("机台校验数据不存在！");
            }
            _mapper.Map(input, entity);
            await _checkReportRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = await _checkReportRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }
    }
}
